package com.dbiservices.dbiworker.run;

import java.net.MalformedURLException;
import java.util.ArrayList;

import javax.xml.bind.JAXBException;

import org.apache.log4j.Logger;

import com.dbiservices.dbiworker.configuration.Context;
import com.dbiservices.dbiworker.model.Model;
import com.dbiservices.dbiworker.model.plugin.Plugin;
import com.dbiservices.dbiworker.model.plugin.PluginHandler;
import com.dbiservices.dbiworker.model.plugin.PluginLoader;
import com.dbiservices.dbiworker.ui.MainWindow;
import com.dbiservices.dbiworker.utils.Map;

public class StartProgram {

	public static void main (String[] args){
		Logger log = Logger.getLogger(StartProgram.class);
		Context.add(Context.iP_PLUGIN_FOLDER, "plugins");
		
		if (args.length>0){
			for (String arg : args){
				if (arg.contains(";")){
					String[] cmds = arg.split(";");
					for (String cmd : cmds){
						Context.add(cmd.split("=")[0], cmd.split("=")[1]);
					}
				}else{
					Context.add(arg.split("=")[0], arg.split("=")[1]);
				}
			}
		}
		Model model = new Model();
		MainWindow window = new MainWindow();
		PluginHandler pHandler = new PluginHandler();
		Context.add(Context.iE_MAIN_MODEL, model);
		Context.add(Context.iE_MAIN_WINDOW, window);
		Context.add(Context.iE_PLUGIN_HANDLER, pHandler);
		model.initialize();
		window.initialize();
		PluginLoader pLoader = new PluginLoader();
		try {
			ArrayList<Plugin> plugins = pLoader.load(pLoader.loadPluginFolders(Context.getString(Context.iP_PLUGIN_FOLDER)));
			Map<String, Plugin>pMap = new Map<String, Plugin>();
			for (Plugin p : plugins){
				pMap.put(p.getPluginName(), p);
				log.info("Loaded module "+p.getPluginName());
			}
			pHandler.setPlugins(pMap);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		for (Plugin p : pHandler.getPlugins().values()){
			p.initialize();
			log.debug("Plugin "+p.getPluginName()+" initialized");
		}
	}
}
